<?php
class model_ConfigMapper {
    private static $mapper;
    private static $timestart;
    private static $sqlcount;


    public static function setTimer() {
        self::$timestart = microtime(true);
    }

    public static function getTimer() {
        return self::$timestart;
    }

    public static function setSqlCounter() {
        self::$sqlcount ++;

    }

    public static function getSqlCounter() {
        return self::$sqlcount;

    }

    public static function instance() {
        if(null == model_ConfigMapper::$mapper) {
            self::$sqlcount = 0;
            model_ConfigMapper::$mapper = new model_ConfigMapper();
        }
        return model_ConfigMapper::$mapper;
    }

    public static function connect() {
        $user = "root";
        $password = "1";
        $link = mysql_connect('localhost', $user, $password) or die('Ошибка подключения: ' .mysql_error());
        mysql_select_db('task4base', $link) or die('Ошибка подключения к базе task4base: ' .mysql_error());
        ;
        mysql_query('set names utf8');
    }

    public static function validate($text) {


        foreach($text as $key=>$val) {
            //сделать вырезание не всех тегов,а только конкретных при помощи прег_матч
            if(is_array($text[$key])) {
                //если приходящий элемент пост является массивом, то обрезаем вражье для каждого элемента
                // пока необходимо только для тегов
                foreach($text[$key] as $index=>$value) {
                    $post[$key][$index] = trim(strip_tags($value));
                }
            } else {
                if('content' == $key) {

                    var_dump($text);
                    exit;

                    $iframe = trim(strip_tags($val,'<iframe>'));
                    $c = strstr($iframe, '<iframe');

                    if ($c) {

                        // проверяем, приходит ли в поле контент тег <iframe>
                        // если да, то разбираем его, смотрим с ютюба он или с вимео
                        // если да, то берем только адрессн а видео и собираем заного
                        // если в айфрейме чтото другое, то делаем его пустым

                        $u = strstr($iframe, 'src="');
                        $url = substr($u,0, 46);

                        if(strstr($url, 'www.youtube.com/embed/')) {
                            $post[$key] = '<iframe width="525" height="325" '. $url .' allowfullscreen></iframe>';
                        } else {

                            $url = substr($u,0, 43); //<iframe width="400" height="225" frameborder="0" allowfullscreen="" mozallowfullscreen="" webkitallowfullscreen="" src="http://player.vimeo.com/video/36825140?title=0&byline=0&portrait=0">

                            if(strstr($url, 'player.vimeo.com/video/')) {
                                $post[$key] = '<iframe width="525" height="325" '. $url .'" allowfullscreen></iframe>';
                            } else {
                                $post[$key] = '';
                            }
                        }
                    } else {
                        $post[$key] = $iframe;
                    }
                    //youtuve - 46 symb
                    //vimeo - 37 symb
                } else {
                    $post[$key] = trim(strip_tags($val));
                }
            }
        }

        return $post;
    }

    public static function ifExist($id, $name, $table) {
        $query = 'SELECT * from task4base.'.$table.' WHERE '. $name .' = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_row($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        if ($row) {
            return true;
        } else {
            return false;
        }
    }

    public static function findAuthor($id) {
        $query = 'SELECT * from task4base.users WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $row['name'] . ' ' . $row['surname'];
    }

    public static function findOwner($id) {
        $query = 'SELECT owner from task4base.photos WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $row['owner'];
    }

    public static function findKarma($id) {
        $query = 'SELECT karma from task4base.users WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);
        
        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $row['karma'];
    }

    public static function findAvatar($id) {
        if (0 == $id) {
            return 'noavatar';
        }

        $query = 'SELECT name from task4base.photos WHERE id = '. $id;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        if ($result) {
            $row = mysql_fetch_array($result);
            return $row['name'];
        } else {
            return 'noavatar';
        }
    }

    public static function findAvatar2($id) {
        $query = 'SELECT avatar from task4base.users WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);
        $img = model_ConfigMapper::findAvatar($row['avatar']);


        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
        return $img;
    }

    public static function getPages($num, $table, $id = null, $col = null) {
        if (null == $id) {
            $query = 'SELECT COUNT(*) AS counter from '.$table;
        } else {
            $query = 'SELECT COUNT(*) AS counter from '.$table.' where '.$col.' = '. $id;
        }
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $elements = $row['counter'];
        $pages = ceil($elements/$num);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $pages;
    }

    public static function getUnread($id) {
        $query = 'SELECT COUNT(*) AS counter from messages where komu =' .$id.' and isread = 0';
        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $count = $row['counter'];

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $count;
    }

    public static function getCount($table, $col, $id) {
        $query = 'SELECT COUNT(*) AS counter from '.$table.' where '.$col.' = '. $id;

        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);

        $count = $row['counter'];

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $count;
    }

    public static function getPaginator($page, $pages, $link) {
        $str = '';
        if(!empty($page) && 1 != $pages) {

            $neighbours = 2;
            $left_neighbours = $page - $neighbours;
            if(1 > $left_neighbours) {
                $left_neighbours = 1;
            }

            $right_neighbours = $page + $neighbours;
            if($pages < $right_neighbours) {
                $right_neighbours = $pages;
            }

            if(1 < $page) {
                $str .= '<a href="'. $link .'&page=1">1</a> ... <a href="?'. $link .'&page='. ($page - 1) .'"><сюда</a> ';
            }

            for ($i=$left_neighbours;$i<=$right_neighbours;$i++) {
                if($i != $page) {
                    $str .= '<a href="?'. $link .'&page='. $i .'">'. $i .'</a> ';
                } else {
                    $str .= '<b>'. $i .'</b> ';
                }
            }

            if($page < $pages) {
                $str .= '<a href="?'. $link .'&page='. ($page + 1) .'">туда></a> ... <a href="?'. $link .'&page='. $pages .'">'. $pages .'</a>';
            }
        }

        return $str;
    }

    public static function getSalt($count) {
        $arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0');
        $salt = '';
        for($i=0;$i<$count;$i++) {
            $index = rand(0, count($arr) - 1);
            $salt .= $arr[$index];
        }
        return $salt;
    }

    public static function sqlValid($post) {
        $sql = mysql_real_escape_string($post);
        return $sql;
    }
}